package com.myjavalab.thread;

public class TwoPhaseTerminationPattern {
	public static void main(String[] args) {
		System.out.println("main begin:");
		try {
			CountUpThread t = new CountUpThread();
			t.start();
			Thread.sleep(10000);
			System.out.println("main : shutdown request");
			t.shutdownRequest();
			t.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("main end:");
	}
}

class CountUpThread extends Thread{
	private long counter = 0;
	private volatile boolean shutdownRequested = false;
	
	public void shutdownRequest() {
		shutdownRequested = true;
		interrupt();
	}
	
	public boolean isShutdownRequested() {
		return shutdownRequested;
	}
	
	public void run() {
		try {
			while(!shutdownRequested) {
				doWork();
			}
		}catch (InterruptedException e) {
			
		}finally {
			doShutdown();
		}
	}
	
	/*
	 * do normal work
	 */
	private void doWork() throws InterruptedException {
		counter++;
		System.out.println("doWork: counter = " + counter);
		Thread.sleep(500);
	}
	
	/*
	 * do something before thread end
	 */
	private void doShutdown() {
		System.out.println("doShutdown: counter = " + counter);
	}
}